﻿#include "ssMaterial.h"
#include "../camera/ssCamera.h"
#include "../../node/ssNode.h"

namespace StarSeeker
{

ssShader*	ssMaterial::s_pShader = 0;

ssMaterial::ssMaterial()
{
	m_type = SS_COMPONENT_MATERIAL;
	m_pShader = 0;
	m_pTransform = 0;
	m_shaderCamera.BindData(SS_GL_UNIFORM_MAT, "inProjMat");
	m_shaderView.BindData(SS_GL_UNIFORM_MAT, "inViewMat");
	m_shaderModel.BindData(SS_GL_UNIFORM_MAT, "inModelMat");
}

ssMaterial::~ssMaterial()
{
}

void ssMaterial::SetShader(ssShader* ps)
{
	m_pShader = ps;
}

void ssMaterial::SwitchShader()
{
	if (m_pShader && m_pShader != ssMaterial::s_pShader)
	{
		m_pShader->Use();
		ssMaterial::s_pShader = m_pShader;
	}
}

void ssMaterial::SetShaderUniform()
{
	if (m_pShader)
	{
		if (ssCamera::s_currentCamera)
		{
			m_shaderCamera.Use(m_pShader, ssCamera::s_currentCamera->GetProjMatrix().m, 4);
			m_shaderView.Use(m_pShader, ssCamera::s_currentCamera->GetViewMatrix().m, 4);
		}
		else
		{
			m_shaderCamera.Use(m_pShader, cg_identityMat4x4.m, 4);
			m_shaderView.Use(m_pShader, cg_identityMat4x4.m, 4);
		}
		if (m_pTransform)
		{
			m_shaderModel.Use(m_pShader, m_pTransform->ViewMatrix().m, 4);
		}
		else
		{
			m_shaderModel.Use(m_pShader, cg_identityMat4x4.m, 4);
		}
	}
}

void ssMaterial::OnRenderBegin()
{
	SetShaderUniform();
}

void ssMaterial::OnRenderEnd()
{
}

void ssMaterial::OnAdd()
{
	m_pTransform = &m_pNode->Transform();
}

}
